package com.delayqueue.core.netty.handler.master;

import com.alibaba.fastjson.JSON;
import com.delayqueue.common.enums.MessageType;
import com.delayqueue.common.netty.NettyMessage;
import com.delayqueue.common.task.Task;
import com.delayqueue.core.queue.QueueHandler;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@ChannelHandler.Sharable
public class MasterMessageHandler extends SimpleChannelInboundHandler<NettyMessage> {

    @Autowired
    private QueueHandler queueHandler;

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, NettyMessage message) throws Exception {
        MessageType messageType = message.getMessageType();
        String messageContent = message.getMessageContent();
        if (messageType == MessageType.TASK_NEW) {
            Task task = JSON.parseObject(messageContent, Task.class);
            queueHandler.addNewTask(task);
        } else if (messageType == MessageType.TASK_DELETE) {
            Task task = new Task(messageContent);
            queueHandler.deleteTask(task);
        }
    }
}
